use std::{fs, path::PathBuf};

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};

/// 配置文件结构体
#[derive(Debug, Deserialize, Serialize)]
pub struct Config {
    /// 数据库连接信息
    pub url: String,
    /// 数据库表列名前缀
    pub prefix: String,
}

impl Config {
    /// 从 TOML 文件加载配置
    pub fn from_file(path: &PathBuf) -> Result<Self> {
        let contents =
            fs::read_to_string(path).with_context(|| format!("无法读取配置文件: {:?}", path))?;

        let config: Config = toml::from_str(&contents)
            .with_context(|| format!("无法解析 TOML 配置文件: {:?}", path))?;

        Ok(config)
    }

    /// 验证配置的有效性
    pub fn validate(&self) -> Result<()> {
        if self.url.is_empty() {
            anyhow::bail!("数据库 URL 不能为空");
        }

        if self.prefix.is_empty() {
            anyhow::bail!("表前缀不能为空");
        }

        Ok(())
    }
}
